using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using Microsoft.MSE.Catalog.Module;
using Microsoft.MSE.Catalog.SelfHost;

namespace Microsoft.MSE.Catalog.ServiceHost
{
    public class CatalogService : ServiceBase
    {
        private readonly CatalogServer _catalogServer = new CatalogServer();
        private readonly EventLogTraceListener m_eventLogListener;

        public CatalogService()
        {
            ServiceName = SC.ComponentName;

            TraceHelper.InitializeTraceSource("mseTraceSrc");

            if (!EventLog.SourceExists(SC.ComponentName))
            {
                EventLog.CreateEventSource(SC.ComponentName, SC.EventLogName);
            }

            m_eventLogListener = new EventLogTraceListener(SC.ComponentName);
            TraceHelper.MseTraceSource.Listeners.Add(m_eventLogListener);
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                //BOTTO redundant.  CatalogServer.Start will trace startup sequence
                //TraceHelper.TraceInformation("Starting " + SC.ComponentName + "...");

                _catalogServer.Start();

                //_catalogServer.StartServiceCompleted += delegate(object sender, StartServiceCompletedEventArgs e)
                //                                            {
                //                                                if (e.Error == null) return;

                //                                                TraceHelper.TraceError("Attempt to start " +
                //                                                                       SC.ComponentName + " failed: " +
                //                                                                       e.Error);
                //                                                Stop();
                //                                            };

                //_catalogServer.StartServiceAsync();
            }
            catch (Exception ex)
            {
                TraceHelper.TraceError("Attempt to start " + SC.ComponentName + " failed: " + ex);
                throw;
            }
        }

        protected override void OnStop()
        {
            try
            {
                _catalogServer.Stop();
            }
            catch (Exception ex)
            {
                TraceHelper.TraceError("Attempt to stop " + SC.ComponentName + " failed: " + ex);
                throw;
            }
        }
    }
}